package dimension.starry.block.typeInterface;

import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.inventory.SimpleInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.screen.ScreenHandlerType;
import net.minecraft.screen.slot.Slot;
import net.minecraft.util.math.BlockPos;
import org.jetbrains.annotations.Nullable;

public abstract class MachineContainer extends ScreenHandler {

    protected final MachineTileEntity machineTileEntity;
    private final PlayerInventory playerInventory;
    private final BlockPos blockPos;

    public MachineContainer(
        @Nullable ScreenHandlerType<?> type, int syncId, PlayerInventory playerInventory, BlockPos blockPos,
        int playerInvX, int playerInvY
    ) {
        super(type, syncId);
        this.machineTileEntity = (MachineTileEntity) playerInventory.player.getEntityWorld().getBlockEntity(blockPos);
        this.playerInventory = playerInventory;
        this.blockPos = blockPos;
        if (this.machineTileEntity != null) {
            this.addProperties(machineTileEntity.getContainerProgress());
        }
        layoutPlayerInventorySlots(playerInventory, playerInvX, playerInvY);
    }

    public MachineTileEntity getMachineTileEntity() {
        return machineTileEntity;
    }

    private void layoutPlayerInventorySlots(Inventory inventory, int leftCol, int topRow) {
        addSlotBox(inventory, 9, leftCol, topRow, 9, 18, 3, 18);
        topRow += 58;
        addSlotRange(inventory, 0, leftCol, topRow, 9, 18);
    }

    protected int addSlotBox(
        Inventory inventory, int index, int x, int y, int horAmount, int dx, int verAmount, int dy
    ) {
        for (int j = 0; j < verAmount; j++) {
            index = addSlotRange(inventory, index, x, y, horAmount, dx);
            y += dy;
        }
        return index;
    }

    protected int addSlotRange(Inventory inventory, int index, int x, int y, int amount, int dx) {
        for (int i = 0; i < amount; i++) {
            addSlot(new Slot(inventory, index, x, y));
            x += dx;
            index++;
        }
        return index;
    }

    @Override
    public ItemStack quickMove(PlayerEntity playerEntity, int slotIndex) {
        return ItemStack.EMPTY;
    }

    @Override
    public boolean canUse(PlayerEntity playerEntity) {
        if (playerEntity.getEntityWorld().getBlockEntity(this.blockPos) != this.getMachineTileEntity()) {
            return false;
        } else {
            return playerEntity.squaredDistanceTo(this.blockPos.getX() + 0.5D, this.blockPos.getY() + 0.5D,
                this.blockPos.getZ() + 0.5D
            ) <= 64.0D;
        }
    }

    public PlayerInventory getPlayerInventory() {
        return playerInventory;
    }

    public BlockPos getBlockPos() {
        return blockPos;
    }
}
